﻿using System;
using System.Configuration;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;

namespace In.Api.Helpers
{
    public static class WsClientFactory
    {
        /// <summary>
        /// 获取 广医三院HIS 当天 Web Service 的代理类
        /// </summary>
        /// <returns></returns>
        public static In.Api.HisWs.PAYWebserviceSoapClient GetHisWsSoapClient()
        {
            var endpointAddress = ConfigurationManager.AppSettings["HisWsUrl"];

            var binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.MaxBufferSize = Int32.MaxValue;

            var ws = new In.Api.HisWs.PAYWebserviceSoapClient(binding, new EndpointAddress(endpointAddress));
            return ws;
        }

        /// <summary>
        ///  Lis 报告 Web Service 的代理类
        /// </summary>
        /// <returns></returns>
        public static In.Api.LisWs.XhlisWebserviceClient GetReportServiceClient()
        {
            var endpointAddress = ConfigurationManager.AppSettings["ReportWsUrl"];

            var binding = new BasicHttpBinding();
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.MaxBufferSize = Int32.MaxValue;

            var ws = new In.Api.LisWs.XhlisWebserviceClient(binding, new EndpointAddress(endpointAddress));
            return ws;
        }


        /// <summary>
        /// 根据私钥和入参XML生成签名
        /// </summary>
        /// <param name="privateKey">私钥</param>
        /// <param name="requestXml">入参XML</param>
        /// <returns></returns>
        public static string signData(string privateKey, string requestXml)
        {
            string sign = null;
            byte[] data = null;
            RSACryptoServiceProvider rsa = null;
            try
            {
                rsa = new RSACryptoServiceProvider();
                rsa.FromXmlString(privateKey);
                data = Encoding.UTF8.GetBytes(requestXml.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\t", ""));
                sign = Convert.ToBase64String(rsa.SignData(data, "SHA1"));
            }
            finally
            {
                if (rsa != null)
                    rsa.Dispose();
                rsa = null;
                data = null;
            }
            return sign;
        }
    }
}